package com.santu.edu.supporter.biz.pay.service.impl;

import com.santu.edu.supporter.biz.order.common.pojo.enums.OrderStatusEnum;
import com.santu.edu.supporter.biz.order.kd.dao.KuaidiOrderDao;
import com.santu.edu.supporter.biz.pay.pojo.constants.WxPayConstants;
import com.santu.edu.supporter.biz.pay.pojo.dto.WxChatBasePayDTO;
import com.santu.edu.supporter.biz.pay.pojo.dto.WxChatPayDTO;
import com.santu.edu.supporter.biz.pay.service.WxOrderService;
import com.santu.edu.supporter.biz.pay.utils.WxPayCallbackUtil;
import com.santu.edu.supporter.biz.pay.utils.WxPayCommon;
import lombok.RequiredArgsConstructor;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Signature;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class WxOrderServiceImpl implements WxOrderService {

    private static final Logger log = LoggerFactory.getLogger(WxOrderServiceImpl.class);
    private final WxPayConstants wxPayConfig;

    private final CloseableHttpClient wxPayClient;

    private final WxPayCallbackUtil wxPayCallbackUtil;

    private final WxPayConstants wxPayConstants;

   private final CloseableHttpClient closeableHttpClient;

    private final KuaidiOrderDao kdOrderDao;


    /**
     * 微信用户调用微信支付
     */
    @Override
    public WxChatPayDTO pay(WxChatBasePayDTO payData) {
        String prepayId = WxPayCommon.wxJsApiPay(wxPayConfig, payData, payData.getOpenId(), wxPayClient);
        WxChatPayDTO wxChatPayDto = new WxChatPayDTO();
        wxChatPayDto.setAppid(wxPayConstants.getAppId());
        wxChatPayDto.setTimeStamp(String.valueOf(System.currentTimeMillis() / 1000));
        wxChatPayDto.setNonceStr(UUID.randomUUID().toString().replaceAll("-", ""));
        wxChatPayDto.setPrepayId("prepay_id=" + prepayId);
        wxChatPayDto.setSignType("RSA");
        wxChatPayDto.setPaySign(getSign(wxChatPayDto.getNonceStr(), wxChatPayDto.getAppid(), wxChatPayDto.getPrepayId(), Long.parseLong(wxChatPayDto.getTimeStamp())));
        return wxChatPayDto;
    }

    /**
     * 订单支付后回调
     */
    @Override
    public Boolean wxOrderCallBack(HttpServletRequest request, HttpServletResponse response) {
        log.info("接受到订单支付成功回调---------------{}",response);
        try {
            Map<String, String> stringMap = wxPayCallbackUtil.wxChatPayCallback(request, response);
            //支付成功
            if (stringMap.get("trade_state").equals("SUCCESS")) {
                //获取订单号
                String orderId = stringMap.get("out_trade_no");
                log.info("订单支付成功,订单号:{}",orderId);
/*                String orderId = outTradeNo.substring(0, outTradeNo.length() - 2);
                String orderType = outTradeNo.substring(outTradeNo.length() - 2);*/
                kdOrderDao.updateOrderStatus(orderId, OrderStatusEnum.TO_BE_PAID,OrderStatusEnum.IN_PROGRESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

/*    *//**
     * 订单退款
     *//*
    @Override
    public Boolean orderRefund(String orderId,Integer orderType) {
        try {
            Order order = baseMapper.selectById(id);
            WxChatRefundDto dto = new WxChatRefundDto();
            dto.setOrderId(order.getOrderNumber());
            String refundOrderId = IdWorker.getIdStr();
            dto.setRefundOrderId(refundOrderId);
            dto.setNotify(WxNotifyConstants.CAMPUS_CARD_REFUND_NOTIFY);
            dto.setRefundMoney(new BigDecimal(order.getOrderAmount()));
            dto.setTotalMoney(new BigDecimal(order.getOrderAmount()));
            String s = WxPayRefundUtil.refundPay(wxPayConstants, dto, closeableHttpClient);
//            System.out.println(s);
            return Result.ok("退款成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("退款失败");
        }
    }*/

    /**
     * 获取签名
     *
     * @param nonceStr  随机数
     * @param appId     微信公众号或者小程序等的appid
     * @param prepay_id 预支付交易会话ID
     * @param timestamp 时间戳 10位
     * @return String 新签名
     */
    String getSign(String nonceStr, String appId, String prepay_id, long timestamp) {

        //从下往上依次生成
        String message = buildMessage(appId, timestamp, nonceStr, prepay_id);
        //签名
        try {
            return sign(message.getBytes("utf-8"));
        } catch (IOException e) {
            throw new RuntimeException("签名异常,请检查参数或商户私钥");
        }
    }

    String sign(byte[] message) {
        try {
            //签名方式
            Signature sign = Signature.getInstance("SHA256withRSA");
            //私钥，通过MyPrivateKey来获取，这是个静态类可以接调用方法 ，需要的是_key.pem文件的绝对路径配上文件名
            sign.initSign(wxPayConstants.getPrivateKey());
            sign.update(message);
            return Base64.getEncoder().encodeToString(sign.sign());
        } catch (Exception e) {
            throw new RuntimeException("签名异常,请检查参数或商户私钥");
        }
    }

    /**
     * 按照前端签名文档规范进行排序，\n是换行
     *
     * @param nonceStr  随机数
     * @param appId     微信公众号或者小程序等的appid
     * @param prepay_id 预支付交易会话ID
     * @param timestamp 时间戳 10位
     * @return String 新签名
     */
    String buildMessage(String appId, long timestamp, String nonceStr, String prepay_id) {
        return appId + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + prepay_id + "\n";
    }
}
